package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Banner;
import cn.wolfcode.query.BannerQuery;
import cn.wolfcode.repository.BannerRepository;
import cn.wolfcode.service.IBannerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BannerServiceImpl implements IBannerService {

    @Autowired
    private BannerRepository repository;
    @Autowired
    private MongoTemplate template;

    @Override
    public void insert(Banner user) {
        repository.save(user);
    }

    @Override
    public void update(Banner user) {
        repository.save(user);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public Banner get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<Banner> listAll() {
        return repository.findAll();
    }

    @Override
    public Page query(BannerQuery qo) {
        Query query = new Query();
        long count = template.count(query, Banner.class);
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(), Sort.Direction.ASC,"_id");
        query.with(pageable);
        List<Banner> list = template.find(query, Banner.class);

        return new PageImpl(list,pageable,count);
    }

    @Override
    public List<Banner> queryBanner(int type) {
        Pageable pageable = PageRequest.of(0,5, Sort.Direction.ASC,"sequence");
        return repository.findByTypeAndState(type,Banner.STATE_NORMAL,pageable);
    }
}
